package com.sgzn.sgpay.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.sgzn.sgpay.enums.ReturnResultState;
import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.exception.SgpayException;
import com.sgzn.sgpay.model.request.*;
import com.sgzn.sgpay.model.response.CurrentPageInfo;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.model.response.result.PulseInfoQueryPageResult;
import com.sgzn.sgpay.persistence.dao.TPulseInfoMapper;
import com.sgzn.sgpay.persistence.domain.TPulseInfo;
import com.sgzn.sgpay.persistence.domain.TPulseInfoExample;
import com.sgzn.sgpay.service.SgsPulseInfoService;
import com.sgzn.sgpay.service.support.SgsResponseUtil;
import com.sgzn.sgpay.util.PageCalculator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 脉冲管理服务接口实现类
 * @author huangsenguang
 * @version Id: SgsPulseInfoServiceImpl.java, v 0.1 2018/4/25 21:03 huangsenguang Exp $$
 */
@Service
@Slf4j
public class SgsPulseInfoServiceImpl implements SgsPulseInfoService {

    @Autowired
    private TPulseInfoMapper tPulseInfoMapper;

    @Override
    public SgsResultResponse<String> addPulseInfo(SgsPulseInfoAddRequest request) {
        TPulseInfo tPulseInfo = new TPulseInfo();
        tPulseInfo.setDeviceId(request.getDeviceId());
        tPulseInfo.setPulseValue(request.getPulseValue());
        tPulseInfo.setCreatedBy(request.getMchId());
        tPulseInfo.setCreatedAt(new Date());
        tPulseInfo.setUpdatedAt(new Date());
        int num = 0 ;
        try{
            num =  tPulseInfoMapper.insertSelective(tPulseInfo);
        }catch (DataAccessException e) {
            log.error("插入响应流水日志异常.{}", e);
        }
        if (num == 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    public SgsResultResponse<String> deletePulseInfo(SgsPulseInfoDeleteRequest request) {
        TPulseInfoExample example = new TPulseInfoExample();
        TPulseInfoExample.Criteria criteria = example.createCriteria();
        criteria.andDeviceIdEqualTo(request.getDeviceId());
        int num = 0 ;
        try{
            num =  tPulseInfoMapper.deleteByExample(example);
        }catch (DataAccessException e) {
            log.error("插入响应流水日志异常.{}", e);
        }
        if (num == 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    public SgsResultResponse<TPulseInfo> queryPulseInfo(SgsPulseInfoQueryRequest request) {
        TPulseInfo tPulseInfo = null;
        TPulseInfoExample tPulseInfoExample = new TPulseInfoExample();
        tPulseInfoExample.createCriteria().andDeviceIdEqualTo(request.getDeviceId());
        List<TPulseInfo> tPulseInfos = tPulseInfoMapper.selectByExample(tPulseInfoExample);
        if (CollectionUtils.isEmpty(tPulseInfos)) {
            throw new SgpayException(SgsResponseCode.C_PULSEINFO_NOT_FOUND.getResponseCode(),SgsResponseCode.C_PULSEINFO_NOT_FOUND.getResponseDesc());
        }
        tPulseInfo = tPulseInfos.get(0);
        return SgsResponseUtil.INSTANCE.success(tPulseInfo);
    }

    @Override
    public SgsResultResponse<String> updatePulseInfo(SgsPulseInfoUpdateRequest request) {
        TPulseInfo record = new TPulseInfo();
        record.setDeviceId(request.getDeviceId());
        record.setPulseValue(request.getPulseValue());
        record.setUpdatedBy(request.getMchId());
        record.setUpdatedAt(new Date());

        TPulseInfoExample example = new TPulseInfoExample();
        TPulseInfoExample.Criteria criteria = example.createCriteria();
        criteria.andDeviceIdEqualTo(request.getDeviceId());
        int num = 0 ;
        try{
            num =  tPulseInfoMapper.updateByExampleSelective(record, example);
        }catch (DataAccessException e) {
            log.error("插入响应流水日志异常.{}", e);
        }
        if (num == 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    public SgsResultResponse<PulseInfoQueryPageResult> queryPage(SgsPulseInfoQueryPageRequest request) {
        try{
            PulseInfoQueryPageResult result = new PulseInfoQueryPageResult();
            TPulseInfoExample example = this.getTPulseInfoExampleByPage(request);
            int totalCount = this.tPulseInfoMapper.countByExample(example);//获取总数
            CurrentPageInfo pageInfo = PageCalculator.getPageInfo(totalCount, request.getPageQueryParam().getPageSize(),
                    request.getPageQueryParam().getCurrentPage());
            StringBuffer clause = new StringBuffer();
            //加上起始和结束行号进行列表查询
            clause.append("created_at desc ");
            clause.append("limit ").append(pageInfo.getStartIndex()).
                    append(",").append(pageInfo.getPageSize());
            example.setOrderByClause(clause.toString());
            List<TPulseInfo> list = tPulseInfoMapper.selectByExample(example);

            result.setPulseInfoList(list);
            result.setCurrentPage(pageInfo.getCurrentPage());
            result.setPageSize(pageInfo.getPageSize());
            result.setTotalCount(totalCount);
            result.setTotalPage(pageInfo.getTotalPage());
            return SgsResponseUtil.INSTANCE.success(result);
        }catch (Exception e){
            log.error("脉冲分页查询系统异常：",e);
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc());
        }
    }

    /**
     * 获取查询对象
     * @param request
     * @return
     */
    private TPulseInfoExample getTPulseInfoExampleByPage(SgsPulseInfoQueryPageRequest request){
        TPulseInfoExample countExample = new TPulseInfoExample();
        TPulseInfoExample.Criteria cra = countExample.createCriteria();
        if(StringUtils.isNotBlank(request.getDeviceId())){
            cra.andDeviceIdEqualTo(request.getDeviceId());
        }
        if(StringUtils.isNotBlank(request.getPulseValue())){
            cra.andPulseValueEqualTo(request.getPulseValue());
        }
        return countExample;
    }
}

